﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;

namespace SerialPort_URAT
{
    public partial class LEV_ST_Monitor_Form : Form, IMessageFilter
    {
        // P/Invoke declarations
        [DllImport("user32.dll")]
        private static extern IntPtr WindowFromPoint(Point pt);
        [DllImport("user32.dll")]
        private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);

        private Form ParentMainForm;
        UInt64 g_ScanningCount = 0;
        //====================================================
        private const short XGap = 5;
        private const short YGap = 5;
        private const short Compont_Width = 60;
        private const short Compont_Height = 5;
        private const short Compont_Label_Width = 135;

        private const short Indication_Label_Width = 50;
        private const short Indication_Label_Height = 12;
        private const float Indication_Label_Font_Size = 8.0f;
        //====================================================



        // save datalog
        string DefaultDataLogFileFolderName = "DP_LEV_Monitor_Record";
        static string DefaultDataLogFileNameHeader = "LEV_Monitor_ST_Solution";
        static string StatusDataLogFileNameHeader = "_STATUS_";
        static string EepromDataLogFileNameHeader = "_EEPROM_";
        private string UserDataLogDefaultFolderPath;
        private string UserDataLogPathFileName;

        private StreamWriter SaveStatusDataLogFileStream;
        private StreamWriter SaveEepromDataLogFileStream;
        private int Status_FileName_Num_Count;
        private int Eeprom_FileName_Num_Count;
        private const int MaxLogFileLine = 10000;
        private int Status_LogFileLineCount = 0;
        private int Eeprom_LogFileLineCount = 0;
        private bool Saving_DataLogFile_Flag = false;
        private bool Create_New_Status_LogFile_Flag = true;
        private bool Create_New_Eeprom_LogFile_Flag = true;

        private bool SaveLogGroupBoxforUser_enable = false;
        private byte[] LastSystemData;
        private byte[] LastEepromData;
        //====================================================

        //====================================================
        // For GUI Setting

        public delegate void MyTextBoxInvoke(TextBox tb, string str1);
        public void UpdateTextBox(TextBox setTextBoxs, string param1)
        {
            setTextBoxs.Text = param1;
        }
        public delegate void MyArrayTextBoxInvoke(TextBox[] tb, string[] str1);
        public void UpdateArrayTextBox(TextBox[] setTextBoxs, string[] param1)
        {
            int length;
            if (setTextBoxs.Length <= param1.Length)
            {
                length = setTextBoxs.Length;
            }
            else
            {
                length = param1.Length;
            }
            for (int i = 0; i < length; i++)
            {
                setTextBoxs[i].Text = param1[i];
            }
        }

        public delegate void MyLabelInvoke(Label lb, string str1);
        public void UpdateLabel(Label setLabel, string param1)
        {
            setLabel.Text = param1;
            if (setLabel.BackColor != Color.Pink)
            {
                setLabel.BackColor = Color.Pink;
            }
            else
            {
                //setLabel.BackColor = SystemColors.Control;
                setLabel.BackColor = Color.HotPink ;
            }
        }
        public delegate void MyArrayLabelInvoke(Label[] lb, string[] str1);
        public void UpdateArrayLabel(Label[] setLabel, string[] param1)
        {
            int length;
            if (setLabel.Length <= param1.Length)
            {
                length = setLabel.Length;
            }
            else
            {
                length = param1.Length;
            } 
            Color currentColor;
            if (setLabel[0].BackColor != Color.Pink)
            {
                currentColor = Color.Pink;
            }
            else
            {
                currentColor = Color.HotPink;
            }

            for (int i = 0; i < length; i++)
            {
                setLabel[i].Text = param1[i];
                setLabel[i].BackColor = currentColor;
            }
        }

        //====================================================
        public LEV_ST_Monitor_Form(Form MainForm, String LogFileName)
        {
            ParentMainForm = MainForm;
            g_ScanningCount = 0;
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;

            Application.AddMessageFilter(this);


            this.panel1.MouseWheel += new System.Windows.Forms.MouseEventHandler(panel1_MouseWheel);
            this.panel2.MouseWheel += new System.Windows.Forms.MouseEventHandler(panel2_MouseWheel);



            InitializeAdditionalFormComponent();

            string MyDocumentsFolder = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            UserDataLogDefaultFolderPath = Path.Combine(MyDocumentsFolder, DefaultDataLogFileFolderName);
            if (!Directory.Exists(UserDataLogDefaultFolderPath))
            {
                //建立指定路徑的資料夾 
                System.IO.Directory.CreateDirectory(UserDataLogDefaultFolderPath);
            }
            

            if (LogFileName.Equals(String.Empty))
            {
                UserDataLogPathFileName = "";
                Saving_DataLogFile_Flag = false;
                SaveLogGroupBoxforUser_enable = true;
                SaveLog_groupBox.Enabled = SaveLogGroupBoxforUser_enable;
            }
            else
            {
                string pathName = Path.Combine(UserDataLogDefaultFolderPath, LogFileName);
                UserDataLogPathFileName = pathName;
                Saving_DataLogFile_Flag = true;
                SaveLogGroupBoxforUser_enable = false;
                SaveLog_groupBox.Enabled = SaveLogGroupBoxforUser_enable;
            }
        }

        public void Set_SaveLog_FileName(String pathFileName)
        {
            UserDataLogPathFileName = pathFileName;
            this.Text = "FA Tool Data Log : " + UserDataLogPathFileName;
        }
        public void SaveLog_Once()
        {
            if (UserDataLogPathFileName.Equals(String.Empty))
            {
                Saving_DataLogFile_Flag = false;
            }
            else
            {
                Saving_DataLogFile_Flag = true;
            }
            if (LastSystemData != null && LastSystemData.Length > 1)
            {
                set_Sys_Status(LastSystemData);
            }
            if (LastEepromData != null && LastEepromData.Length > 1)
            {
                Set_Flash_Values(LastEepromData);
            }
            Saving_DataLogFile_Flag = false;

            this.Refresh();
            MessageBox.Show("Log File (" + UserDataLogPathFileName + ") : saved.");
        }
        //###############################################################################################
        //###############################################################################################
        //  Set DAta to GUI function
        //###############################################################################################
        //###############################################################################################

        public void Set_Flash_Values(byte[] values)
        {
            //ref Label[] showValuesLabel
            string[] outValues;
            LastEepromData = (byte[])values.Clone();
            SetTwoColumnFlashValues(values, ref G_CongifSegmentValuesLabel, G_CongifSegmentDataType, out outValues);
            if (Saving_DataLogFile_Flag)
            {
                if (Create_New_Eeprom_LogFile_Flag)
                {
                    StartEepromFileStreamWriter();
                    SavingEepromFileLogStreamWriter(outValues);
                    Create_New_Eeprom_LogFile_Flag = false;
                }
                else
                {
                    SavingEepromFileLogStreamWriter(outValues);
                    if (Eeprom_LogFileLineCount >= MaxLogFileLine)
                    {
                        ClosingEepromFileLogStreamWriter();
                        Create_New_Eeprom_LogFile_Flag = true;
                    }
                }
            }//if (Saving_DataLogFile_Flag)
        }
        public void set_Sys_Status(byte[] values)
        {
            int dataLength;

            int arrayIndex;

            string[] outValues;
            //GlobalValues
            LastSystemData = (byte[])values.Clone();
            SetTwoColumnTextBoxValues(values, ref GlobalValuesText, out outValues);


            byte[] val = new byte[2];

            arrayIndex = 0;

            dataLength = (short)(((short)values[arrayIndex++] << 8) + values[arrayIndex++]);

            SetCurrentStatusData((short)(((short)values[arrayIndex++] << 8) + values[arrayIndex++]), ref SysModeStatusText, ref SysModeStatusLabel);

            val[1] = values[arrayIndex++];//receive first is high byte.
            val[0] = values[arrayIndex++];//receive second is low byte.
            Set2BytesIndicationData(val, ref G_SysModuleStatusLabel);    //set first array as Low byte, set second array as high byte;

            val[1] = values[arrayIndex++];
            val[0] = values[arrayIndex++];
            Set2BytesIndicationData(val, ref G_Module_Function_StatusLabel);


            val[1] = values[arrayIndex++];
            val[0] = values[arrayIndex++];
            Set2BytesIndicationData(val, ref G_Add_Module_Function_StatusLabel);


            val[1] = values[arrayIndex++];
            val[0] = values[arrayIndex++];
            Set2BytesIndicationData(val, ref G_Device_Interface_Status1Label);

            val[1] = values[arrayIndex++];
            val[0] = values[arrayIndex++];
            Set2BytesIndicationData(val, ref G_Add_Device_Interface_StatusLabel);

            val[1] = values[arrayIndex++];
            val[0] = values[arrayIndex++];
            Set2BytesIndicationData(val, ref G_Capacity_Var_Bits_StatusLabel);

            if (Saving_DataLogFile_Flag)
            {
                if (Create_New_Status_LogFile_Flag)
                {
                    StartStatusFileStreamWriter();
                    SavingStatusFileLogStreamWriter(outValues);
                    Create_New_Status_LogFile_Flag = false;
                }
                else
                {
                    SavingStatusFileLogStreamWriter(outValues);
                    if (Status_LogFileLineCount >= MaxLogFileLine)
                    {
                        ClosingStatusFileLogStreamWriter();
                        Create_New_Status_LogFile_Flag = true;
                    }
                }
            }//if (Saving_DataLogFile_Flag)

            //val = new byte[ADCRecordDataText.Length * 2];
            //Array.Copy(values, arrayIndex, val, 0, ADCRecordDataText.Length * 2);
            //SetTwoColumnTextBoxValues(val, ref ADCRecordDataText);

        }//public void set_Sys_Status(byte[] values)

        //###############################################################################################
        //###############################################################################################
        //  Save Status Data log
        //###############################################################################################
        //###############################################################################################
        private void StartStatusFileStreamWriter()
        {
            int y;
            Status_FileName_Num_Count++;
            Status_LogFileLineCount = 0;
            try
            {
                /////////////////////////////////////////////////////////
                // All moduel 1,2,3
                //SaveDataLogFileStream
                FileStream fsFile = new FileStream(UserDataLogPathFileName + "_" + DefaultDataLogFileNameHeader + StatusDataLogFileNameHeader + String.Format("_{0:0}_", Status_FileName_Num_Count) + ".CSV", FileMode.Create);
                SaveStatusDataLogFileStream = new StreamWriter(fsFile, Encoding.Default);  //使用與系統一致的碼方式
                // Add some text to the file.
                SaveStatusDataLogFileStream.WriteLine("----------------------------------");
                SaveStatusDataLogFileStream.WriteLine("This is the header for the file.");
                SaveStatusDataLogFileStream.WriteLine("The File Name: " + fsFile.Name);
                SaveStatusDataLogFileStream.Write("The date is: ");
                SaveStatusDataLogFileStream.WriteLine(DateTime.Now);
                SaveStatusDataLogFileStream.WriteLine("----------------------------------");

                SaveStatusDataLogFileStream.Write("Index, ");
                for (y = 0; y < GlobalValuesLabel.Length; y++)
                {
                    SaveStatusDataLogFileStream.Write(GlobalValuesLabel[y].Text + ", ");
                }

                SaveStatusDataLogFileStream.WriteLine(" ");
            }
            catch (Exception excep)
            {
                MessageBox.Show("檔案開啟錯誤\n" + excep, "Error");
                if (SaveStatusDataLogFileStream != null)
                {
                    SaveStatusDataLogFileStream.Close();
                }
                //throw excep;
            }
        }//private void StartStatusFileStreamWriter()
        private void SavingStatusFileLogStreamWriter(string[] valuesText)
        {
            int idx = 0;

            SaveStatusDataLogFileStream.Write(String.Format("{0}, ", Status_LogFileLineCount));
            for (int y = 0; y < valuesText.Length; y++)
            {
                SaveStatusDataLogFileStream.Write(valuesText[y] + ", ");
            }

            SaveStatusDataLogFileStream.WriteLine(" " + DateTime.Now);

            Status_LogFileLineCount++;
            SaveStatusDataLogFileStream.Flush();
        }//private void SavingStatusFileLogStreamWriter()

        private void ClosingStatusFileLogStreamWriter()
        {
            /////////////////////////////////////////////////////////
            // All moduel 1,2,3
            //SaveDataLogFileStream
                if (SaveStatusDataLogFileStream != null)
                {
                    SaveStatusDataLogFileStream.WriteLine("----------------------------------");
                    SaveStatusDataLogFileStream.Write("The end date is: ");
                    SaveStatusDataLogFileStream.WriteLine(DateTime.Now);
                }
                if (SaveStatusDataLogFileStream != null)
                {
                    SaveStatusDataLogFileStream.Close();
                }

                Status_LogFileLineCount = 0;
        }//private void ClosingStatusFileLogStreamWriter()


        //###############################################################################################
        //###############################################################################################
        //  Save EEPROM Data log
        //###############################################################################################
        //###############################################################################################
        private void StartEepromFileStreamWriter()
        {
            int y;
            Eeprom_FileName_Num_Count++;
            Eeprom_LogFileLineCount = 0;
            try
            {
                /////////////////////////////////////////////////////////
                // All moduel 1,2,3
                //SaveDataLogFileStream
                FileStream fsFile = new FileStream(UserDataLogPathFileName + "_" + DefaultDataLogFileNameHeader + EepromDataLogFileNameHeader + String.Format("_{0:0}_", Eeprom_FileName_Num_Count) + ".CSV", FileMode.Create);
                SaveEepromDataLogFileStream = new StreamWriter(fsFile, Encoding.Default);  //使用與系統一致的碼方式
                // Add some text to the file.
                SaveEepromDataLogFileStream.WriteLine("----------------------------------");
                SaveEepromDataLogFileStream.WriteLine("This is the header for the file.");
                SaveEepromDataLogFileStream.WriteLine("The File Name: " + fsFile.Name);
                SaveEepromDataLogFileStream.Write("The date is: ");
                SaveEepromDataLogFileStream.WriteLine(DateTime.Now);
                SaveEepromDataLogFileStream.WriteLine("----------------------------------");

                SaveEepromDataLogFileStream.Write("Index, ");
                for (y = 0; y < G_CongifSegmentTextLabel.Length; y++)
                {
                    SaveEepromDataLogFileStream.Write(G_CongifSegmentTextLabel[y].Text + ", ");
                }

                SaveEepromDataLogFileStream.WriteLine(" ");
            }
            catch (Exception excep)
            {
                MessageBox.Show("檔案開啟錯誤\n" + excep, "Error");
                if (SaveEepromDataLogFileStream != null)
                {
                    SaveEepromDataLogFileStream.Close();
                }
                //throw excep;
            }
        }//private void StartEepromFileStreamWriter()
        private void SavingEepromFileLogStreamWriter(string[] valuesText)
        {
            int idx = 0;

            SaveEepromDataLogFileStream.Write(String.Format("{0}, ", Eeprom_LogFileLineCount));
            for (int y = 0; y < valuesText.Length; y++)
            {
                SaveEepromDataLogFileStream.Write(valuesText[y] + ", ");
            }

            SaveEepromDataLogFileStream.WriteLine(" " + DateTime.Now);

            Eeprom_LogFileLineCount++;
            SaveEepromDataLogFileStream.Flush();
        }//private void SavingEepromFileLogStreamWriter()

        private void ClosingEepromFileLogStreamWriter()
        {
            /////////////////////////////////////////////////////////
            // All moduel 1,2,3
            //SaveDataLogFileStream
            if (SaveEepromDataLogFileStream != null)
            {
                SaveEepromDataLogFileStream.WriteLine("----------------------------------");
                SaveEepromDataLogFileStream.Write("The end date is: ");
                SaveEepromDataLogFileStream.WriteLine(DateTime.Now);
            }
            if (SaveEepromDataLogFileStream != null)
            {
                SaveEepromDataLogFileStream.Close();
            }

            Eeprom_LogFileLineCount = 0;
        }//private void ClosingEepromFileLogStreamWriter()
        //###############################################################################################
        //###############################################################################################
        //  Set GUI function
        //###############################################################################################
        //###############################################################################################
        private void setGUIGroupBoxContainForTwoColumnTextBox(ref string[] showStr, ref Label[] showTextLabel, ref TextBox[] showValuesTextBox, ref GroupBox groupBox)
        {
            int i, j;
            int group_left_pos = 10;
            int group_top_pos = 30;
            int label_x_pos = 0, label_y_pos = 0;
            int textBox_x_pos = 0, textBox_y_pos = 0;
            int max_Label_Width = 0;
            int max_textBox_Width = 0;

            showValuesTextBox[0] = new TextBox();
            int TextBoxHeight = showValuesTextBox[0].Height;

            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos;
            //for (i = 0; i < UserDataCmdNum; i++)
            for (i = 0; i < showStr.Length; i++)
            {
                showTextLabel[i] = new Label();
                showTextLabel[i].AutoSize = true;
                showTextLabel[i].Text = showStr[i].Trim(); ;
                showTextLabel[i].Location = new Point(label_x_pos, label_y_pos);
                showTextLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                groupBox.Controls.Add(showTextLabel[i]);
                label_y_pos += YGap + TextBoxHeight;
                if (showTextLabel[i].Width > max_Label_Width)
                {
                    max_Label_Width = showTextLabel[i].Width;
                }
            }
            for (i = 0; i < showStr.Length; i++)
            {
                showTextLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showTextLabel[i].AutoSize = false;
                showTextLabel[i].Width = max_Label_Width;
            }


            textBox_x_pos = group_left_pos + XGap + max_Label_Width;
            textBox_y_pos = group_top_pos;
            for (i = 0; i < showStr.Length; i++)
            {
                showValuesTextBox[i] = new TextBox();
                showValuesTextBox[i].Width = Compont_Width;
                showValuesTextBox[i].ReadOnly = true;
                showValuesTextBox[i].Location = new Point(textBox_x_pos, textBox_y_pos);
                textBox_y_pos += YGap + showValuesTextBox[i].Height;
                groupBox.Controls.Add(showValuesTextBox[i]);
                if (showValuesTextBox[i].Width > max_textBox_Width)
                {
                    max_textBox_Width = showValuesTextBox[i].Width;
                }
            }

            groupBox.Height = textBox_y_pos;
            groupBox.Width = group_left_pos + XGap + max_Label_Width + XGap + max_textBox_Width;
            groupBox.Text = groupBox.Text + "   (w=" + groupBox.Width + ", h=" + groupBox.Height + ")";
        }


        private int SetTwoColumnTextBoxValues(byte[] value, ref TextBox[] setTextBoxs, out string[] out_Text_Values)
        {
            int i;
            int val;
            int count = 0;

            /*
            for (i = 0; i < setTextBoxs.Length; i++)
            {
                val = value[count]; 
                count++;
                val = val << 8; 
                val = val + value[count]; 
                count++;

                MyTextBoxInvoke mi = new MyTextBoxInvoke(UpdateTextBox);
                this.BeginInvoke(mi, new Object[] { setTextBoxs[i], String.Format("{0:0}", val) });
                //setTextBoxs[i].Text = String.Format("{0:0}", val);
            }
            */
            //string[] str = new string[setTextBoxs.Length];
            string[] str = new string[value.Length/2];
            //for (i = 0; i < setTextBoxs.Length; i++)
            for (i = 0; i < str.Length; i ++)
            {
                val = value[count];
                count++;
                val = val << 8;
                val = val + value[count];
                count++;
                str[i] = String.Format("{0:0}", val);
            }
            MyArrayTextBoxInvoke mi = new MyArrayTextBoxInvoke(UpdateArrayTextBox);
            this.BeginInvoke(mi, new Object[] { setTextBoxs.Clone(), str.Clone () });

            out_Text_Values = (string[])str.Clone();

            return count;
        }
        //###############################################################################################

        private void setGUIGroupBoxContainFor2Line2BytesIndication(ref string[] showStr, ref Label[] showLabel, ref GroupBox groupBox)
        {

            int i, j;
            int group_left_pos = 10;
            int group_top_pos = 20;
            int label_x_pos = 0, label_y_pos = 0;


            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos;
            for (i = 0; i < 8; i++)
            {
                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            groupBox.Width = label_x_pos + XGap;

            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos + showLabel[0].Height;
            for (i = 8; i < 16; i++)
            {
                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            label_x_pos = group_left_pos;
            label_y_pos += showLabel[0].Height + YGap;
            groupBox.Height = label_y_pos + YGap;

            groupBox.Text = groupBox.Text + "   (w=" + groupBox.Width + ", h=" + groupBox.Height + ")";
        }

        //###############################################################################################
        private void setGUIGroupBoxContainFor4Line2BytesIndication(ref string[] showStr, ref Label[] showLabel, ref GroupBox groupBox)
        {
            int i;
            int group_left_pos = 10;
            int group_top_pos = 20;
            int label_x_pos = 0, label_y_pos = 0;

            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos;
            for (i = 0; i < 4; i++)
            {

                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width * 2;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            groupBox.Width = label_x_pos + XGap;

            label_x_pos = group_left_pos;
            label_y_pos = label_y_pos + showLabel[0].Height;
            for (i = 4; i < 8; i++)
            {
                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width * 2;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            label_x_pos = group_left_pos;
            label_y_pos = label_y_pos + showLabel[0].Height;
            for (i = 8; i < 12; i++)
            {
                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width * 2;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            label_x_pos = group_left_pos;
            label_y_pos = label_y_pos + showLabel[0].Height;
            for (i = 12; i < 16; i++)
            {
                showLabel[i] = new Label();
                showLabel[i].Width = Indication_Label_Width * 2;
                showLabel[i].Text = showStr[i];
                showLabel[i].Font = new Font(showLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showLabel[i].Height = Indication_Label_Height;
                showLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showLabel[i]);
                label_x_pos += showLabel[i].Width;
            }
            groupBox.Height = label_y_pos + showLabel[0].Height + YGap;
            groupBox.Text = groupBox.Text + "   (w=" + groupBox.Width + ", h=" + groupBox.Height + ")";
        }//private void set4LineIndicationGroupBoxContain(ref string[] showStr, ref Label[] showLabel, ref GroupBox groupBox)
        //###############################################################################################
        //set first array as Low byte, set second array as high byte;
        public void Set2BytesIndicationData(byte[] status, ref Label[] setLabels)
        {
            //set first as Low byte, set second as high byte;
            int i;
            byte compareBit = 0x80;

            for (i = 0; i < 8; i++)
            {
                if ((status[1] & compareBit) > 0)
                {
                    setLabels[i].BackColor = Color.Red;
                }
                else
                {
                    setLabels[i].BackColor = Color.LightGray;
                }
                compareBit >>= 1;
            }
            compareBit = 0x80;
            for (i = 8; i < 16; i++)
            {
                if ((status[0] & compareBit) > 0)
                {
                    setLabels[i].BackColor = Color.Red;
                }
                else
                {
                    setLabels[i].BackColor = Color.LightGray;
                }
                compareBit >>= 1;
            }
        }//public void Set2BytesIndicationData(byte[] status, ref Label[] setLabels)
        //###############################################################################################
        private void setGUIGroupBoxContainFor_Flash_2_ColumnLabels(ref string[] showStr, ref Label[] showTextLabel, ref Label[] showValuesLabel, ref GroupBox groupBox)
        {
            //G_CongifSegmentText
            //private Label[] G_CongifSegmentTextLabel;
            //private Label[] G_CongifSegmentValuesLabel;
            //G_CongifSegmentChar = new char[G_CongifSegmentText.Length];

            int i, j;
            int group_left_pos = 5;
            int group_top_pos = 15;
            int label_x_pos = 0, label_y_pos = 0;

            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos;
            for (i = 0; i < showStr.Length; i++)
            {
                showTextLabel[i] = new Label();
                showTextLabel[i].Width = 320;
                showTextLabel[i].Text = showStr[i].Trim();
                showTextLabel[i].Font = new Font(showTextLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showTextLabel[i].Height = Indication_Label_Height;
                showTextLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showTextLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showTextLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showTextLabel[i]);
                label_y_pos += Indication_Label_Height;
            }
            //ConfigSegmentGroupBox.Width = label_x_pos + XGap;
            label_x_pos = label_x_pos + G_CongifSegmentTextLabel[0].Width + XGap;
            label_y_pos = group_top_pos;
            for (i = 0; i < showStr.Length; i++)
            {
                showValuesLabel[i] = new Label();
                showValuesLabel[i].Width = Compont_Label_Width;
                showValuesLabel[i].Text = "-";
                showValuesLabel[i].Font = new Font(showValuesLabel[i].Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
                showValuesLabel[i].Height = Indication_Label_Height;
                showValuesLabel[i].TextAlign = ContentAlignment.MiddleCenter;
                showValuesLabel[i].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
                showValuesLabel[i].Location = new Point(label_x_pos, label_y_pos);
                groupBox.Controls.Add(showValuesLabel[i]);
                label_y_pos += Indication_Label_Height;
            }
            groupBox.Width = label_x_pos + showValuesLabel[0].Width + XGap;
            groupBox.Height = label_y_pos + YGap;
            groupBox.Text = groupBox.Text + "   (w=" + groupBox.Width + ", h=" + groupBox.Height + ")";
        }// private void setTwoColumnIndicationValuesGroupBoxContain(ref string[] showStr, ref Label[] showLabel, ref GroupBox groupBox)
        public int SetTwoColumnFlashValues(byte[] status, ref Label[] showValuesLabel, string[] charDataLength, out string[] out_Text_Values)
        {
            int i;
            int index = 0;
            string str;
            string showTextString = "";
            string[] ArrayStr = new string[showValuesLabel.Length];
            int status_Max_Index = status.Length - 1;

            try
            {

                for (i = 0; i < showValuesLabel.Length; i++)
                {

                    str = charDataLength[i].Trim();

                    if (str.Contains("_uchar_") || str.Contains("_str_len_"))
                    {
                        showTextString = String.Format("{0:0}", status[index]);
                        index += 1;
                    }
                    else if (str.Contains("_str_") && !str.Contains("_str_len_"))
                    {
                        //string str = System.Text.Encoding.Default.GetString(byteArray);
                        byte[] strByte = new byte[status[index - 1]];
                        Array.Copy(status, index, strByte, 0, strByte.Length);
                        showTextString = System.Text.Encoding.Default.GetString(strByte);
                        index = index + status[index - 1];
                    }
                    else if (str.Contains("_char_"))
                    {
                        showTextString = String.Format("{0:0}", (sbyte)status[index]);
                        index += 1;
                    }
                    else if (str.Contains("_int_"))
                    {
                        showTextString = String.Format("{0:0}", ((int)status[index] << 8 | status[index + 1]));
                        index += 2;
                    }
                    else if (str.Contains("_uint_"))
                    {
                        showTextString = String.Format("{0:0}", ((UInt16)status[index] << 8 | status[index + 1]));
                        index += 2;
                    }
                    else if (str.Contains("_float_") || str.Contains("_double_"))
                    {
                        float tempf = 0.0f;
                        unsafe
                        {
                            byte* byteTemp = (byte*)&tempf;
                            *byteTemp++ = status[index + 3];
                            *byteTemp++ = status[index + 2];
                            *byteTemp++ = status[index + 1];
                            *byteTemp++ = status[index];
                        }

                        int lu = status[index ] << 24;
                        lu += status[index + 1] << 16;
                        lu += status[index + 2] << 8;
                        lu += status[index + 3];
                        byte[] floatVals = BitConverter.GetBytes(lu);
                        float f = BitConverter.ToSingle(floatVals, 0);

                        index += 4;
                        //showTextString = String.Format("{0:0.00000}", tempf);
                        showTextString = String.Format("{0:0.00000}", f);

                    }
                    else if (str.Contains("_long_"))
                    {
                        long temp = 0;
                        temp += status[index] << 24;
                        temp += status[index + 1] << 16;
                        temp += status[index + 2] << 8;
                        temp += status[index + 3];
                        showTextString = String.Format("{0:0}", temp);
                        index += 4;
                    }
                    else if (str.Contains("_ulong_"))
                    {
                        UInt64 temp = 0;
                        temp += (UInt64)(status[index] << 24);
                        temp += (UInt64)(status[index + 1] << 16);
                        temp += (UInt64)(status[index + 2] << 8);
                        temp += (UInt64)(status[index + 3]);
                        showTextString = String.Format("{0:0}", temp);
                        index += 4;
                    }
                    else
                    {
                        showTextString = "_";
                    }

                    //MyLabelInvoke mi = new MyLabelInvoke(UpdateLabel);
                    //this.BeginInvoke(mi, new Object[] { showValuesLabel[i], String.Format("{0:0}", showTextString) });
                    ArrayStr[i] = showTextString;
                    if (index > status_Max_Index)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
            }

            MyArrayLabelInvoke mi = new MyArrayLabelInvoke(UpdateArrayLabel);
            this.BeginInvoke(mi, new Object[] { showValuesLabel.Clone(), ArrayStr.Clone() });
            out_Text_Values = (string[])ArrayStr.Clone();
            return index;
        }//public void SetTwoColumnFlashValues(byte[] status, ref Label[] showValuesLabel, char[] charDataLength)
        //###############################################################################################
        private void setGUIGroupBoxContainForCurrentStatus(ref string[] showStr, ref Label showValuesLabel, ref GroupBox groupBox)
        {
            int i, j;
            int group_left_pos = 10;
            int group_top_pos = 20;
            int label_x_pos = 0, label_y_pos = 0;

            label_x_pos = group_left_pos;
            label_y_pos = group_top_pos;
            //SysModeStatusCode
            //Label CurrentStatusLabel = new Label();
            showValuesLabel.Width = 100;
            showValuesLabel.Text = showStr[0];
            showValuesLabel.Font = new Font(showValuesLabel.Font.Name, Indication_Label_Font_Size, FontStyle.Underline);
            showValuesLabel.Height = Indication_Label_Height;
            showValuesLabel.TextAlign = ContentAlignment.MiddleCenter;
            showValuesLabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            showValuesLabel.Location = new Point(label_x_pos, label_y_pos);
            groupBox.Controls.Add(showValuesLabel);
            label_x_pos = group_left_pos + showValuesLabel.Width;
            label_y_pos += showValuesLabel.Height + YGap;
            groupBox.Width = label_x_pos + XGap;
            groupBox.Height = label_y_pos;
        }
        //###############################################################################################
        public void SetCurrentStatusData(Int16 currentValues, ref string[] showStr, ref Label setLabel)
        {
            string str= showStr[currentValues];
            MyLabelInvoke mi = new MyLabelInvoke(UpdateLabel);


            g_ScanningCount++;
            this.BeginInvoke(mi, new Object[] { ScanningCountLabel, g_ScanningCount.ToString() });

            this.BeginInvoke(mi, new Object[] { setLabel, str });
            

            
            //setLabel.Text = showStr[currentValues];
        }//public void SetCurrentStatusData(Int16 currentValues, ref Label[] setLabels)


        private void LEV_ST_Monitor_Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            ClosingStatusFileLogStreamWriter();
            ClosingEepromFileLogStreamWriter();

        }

        private void saveLog_button_Click(object sender, EventArgs e)
        {
            this.SaveLog_Once();
        }

        private void FocusOnMainWinButton_Click_1(object sender, EventArgs e)
        {
            ParentMainForm.Focus();
        }

        private void panel1_MouseWheel(object sender, MouseEventArgs e)
        {
            // 滾輪向上滾 e.Delta = 正數.
            // 滾輪向下滾 e.Delta = 負數.
            //panel1.VerticalScroll.Value += 1;
            //panel1.Refresh();
            //panel1.Invalidate();
            //panel1.Update();

        }
        private void panel2_MouseWheel(object sender, MouseEventArgs e)
        {
        }

        private void panel1_MouseEnter(object sender, EventArgs e)
        {
            //panel1.Focus();
        }

        private void panel1_MouseLeave(object sender, EventArgs e)
        {
        }

        private void panel2_MouseEnter(object sender, EventArgs e)
        {
            //panel2.Focus();
        }
        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == 0x20a)/*WM_MOUSEWHEEL*/
            {
                // By returning true underlying Windows Procedure 
                // will assume this message has been taken care of.

                // WM_MOUSEWHEEL, find the control at screen position m.LParam
                Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
                IntPtr hWnd = WindowFromPoint(pos);
                if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null)
                {
                    SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
                    return true;
                }
            }
            return false;
        }



        //###############################################################################################
 
        //###############################################################################################

        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
        //###############################################################################################
    }
}
